//
//  ADGradientLabel.swift
//  ADKit
//
//  Created by Adoma on 2024/11/1.
//

import UIKit

public class ADGradientLabel: UILabel {
    
    public var colors: [UIColor] = []
    public var locations: [NSNumber] = []
    public var startPoint = CGPoint.zero
    public var endPoint = CGPoint(x: 1, y: 0)
        
    public override func drawText(in rect: CGRect) {
        
        defer {
            super.drawText(in: rect)
        }
        
        if colors.isEmpty {
            return
        }
        
        if colors.count == 1 {
            self.textColor = colors.first
            return
        }
        
        if locations.count != colors.count {
            let lastIndex = colors.endIndex - 1
            locations = colors.indices.map {
                let value = Double($0) / Double(lastIndex)
                return NSNumber(floatLiteral: value)
            }
        }
        
        var size = bounds.size
        
        if let contentBounds = layer.sublayers?.first?.bounds {
            size.width = max(contentBounds.width, size.width)
            size.height = max(contentBounds.height, size.height)
        }
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = .init(origin: .zero, size: size)
        gradientLayer.colors = colors.map({ $0.cgColor })
        gradientLayer.locations = locations
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        
        let renderer = UIGraphicsImageRenderer(size: size)
        let image = renderer.image { context in
            gradientLayer.render(in: context.cgContext)
        }
        
        let color = UIColor(patternImage: image)        
        self.textColor = color
        
    }

}
